package routers

import (
	"time"

	"github.com/gin-gonic/gin"
	"hass.tree.com/bridge/auth"
	"hass.tree.com/bridge/model"
	"hass.tree.com/bridge/vo"
)

func LoadAuth(e *gin.Engine) {
	authRoute := e.Group("/auth")
	{
		authRoute.POST("/login", login)
	}

}
func login(c *gin.Context) {
	var loginData vo.Login
	if err := c.ShouldBindJSON(&loginData); err != nil {
		vo.Fail(err.Error(), c)
		return
	}

	user := model.FindByUsername(loginData.Username)
	if user.Username == "" {
		vo.Fail("用户不存在", c)
		return
	}
	if user.Username != loginData.Password && user.Password != loginData.Password {
		vo.Fail("密码错误", c)
		return
	}

	var expireTime = time.Now().Add(2 * time.Hour)
	if token, err := auth.GenerateToken(user.ID, expireTime); err != nil {
		vo.Fail(err.Error(), c)
	} else {
		vo.Success(token, c)
	}

}
